package com.atguigu.guli.service.sms.controller.api;

import com.atguigu.guli.service.base.result.R;
import com.atguigu.guli.service.base.result.ResultCodeEnum;
import com.atguigu.guli.service.sms.service.SmsService;
import com.atguigu.guli.service.sms.util.FormUtils;
import com.atguigu.guli.service.sms.util.RandomUtils;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.concurrent.TimeUnit;

/**
 * @author dyqstart
 * @create 2021-07-14-19:45
 * @since 1.0.0
 */
@Slf4j
//@CrossOrigin // 跨域
@RestController
@Api(tags = "短信管理")
@RequestMapping("/api/sms")
public class ApiSmsController {

    @Autowired
    private SmsService smsService;
    @Autowired
    private RedisTemplate redisTemplate;

    @GetMapping("send/{mobile}")
    public R send(@PathVariable String mobile){

        /*
        若手机号为空或者不符合手机号格式,则返回“手机号输入不正确”
         */
        if (StringUtils.isEmpty(mobile) || !FormUtils.isMobile(mobile)){
            return R.setResult(ResultCodeEnum.LOGIN_PHONE_ERROR);
        }

        //生成验证码
        String checkCode = RandomUtils.getFourBitRandom();
        //发送短信
        smsService.sendSms(mobile,checkCode);
        //将手机号存入redis
        redisTemplate.opsForValue().set("checkCode:"+ mobile,checkCode,5,TimeUnit.MINUTES);

        return R.ok().message("短信发送成功");
    }
}
